package cn._51doit.flink.day07;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * 使用ProcessFunction注册定时器，实现类似滚动窗口的功能
 *
 * 每个key都有自己的定时器，如果一个key注册了多个相同时间的定时器，后面注册的定时器会覆盖前面注册的定时器，
 * 即相同时间的定时器只会执行一次
 *
 */
public class ProcessFunctionTimerDemo2 {

    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        //spark,1
        DataStreamSource<String> lines = env.socketTextStream("localhost", 8888);

        SingleOutputStreamOperator<Tuple2<String, Integer>> tpStream = lines.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String value) throws Exception {
                String[] fields = value.split(",");
                return Tuple2.of(fields[0], Integer.parseInt(fields[1]));
            }
        });

        //先keyby再使用定时器
        KeyedStream<Tuple2<String, Integer>, String> keyedStream = tpStream.keyBy(t -> t.f0);

        SingleOutputStreamOperator<Tuple2<String, Integer>> res = keyedStream.process(new KeyedProcessFunction<String, Tuple2<String, Integer>, Tuple2<String, Integer>>() {

            private transient ValueState<List<Tuple2<String, Integer>>> listState;

            @Override
            public void open(Configuration parameters) throws Exception {
                ValueStateDescriptor<List<Tuple2<String, Integer>>> stateDescriptor = new ValueStateDescriptor<>("list-state", TypeInformation.of(new TypeHint<List<Tuple2<String, Integer>>>() {
                }));
                listState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public void processElement(Tuple2<String, Integer> value, Context ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                //不输出数据，注册定时器
                long currentTime = System.currentTimeMillis();
                long triggerTime = currentTime - currentTime % 60000 + 60000;
                System.out.println("Register timer : in sumtask : " + getRuntimeContext().getIndexOfThisSubtask() + " at time: " + currentTime);

                List<Tuple2<String, Integer>> list = listState.value();
                if (list == null) {
                    list = new ArrayList<>();
                }
                //进入的数据添加到List中
                list.add(value);
                //更新状态
                listState.update(list);

                ctx.timerService().registerProcessingTimeTimer(triggerTime);

            }

            /**
             * 定时器触发时，会执行onTimer方法
             * @param timestamp
             * @param ctx
             * @param out
             * @throws Exception
             */
            @Override
            public void onTimer(long timestamp, OnTimerContext ctx, Collector<Tuple2<String, Integer>> out) throws Exception {
                System.out.println("onTimer method invoked : in sumtask :" + getRuntimeContext().getIndexOfThisSubtask() + " at time: " + timestamp);

                List<Tuple2<String, Integer>> list = listState.value();
                //将数据按照次数进行排序，输出次数最大的前3个
                list.sort(new Comparator<Tuple2<String, Integer>>() {
                    @Override
                    public int compare(Tuple2<String, Integer> o1, Tuple2<String, Integer> o2) {
                        return o2.f1 - o1.f1;
                    }
                });

                for (int i = 0; i < Math.min(list.size(), 3); i++) {
                    out.collect(list.get(i));
                }

                list.clear();

            }
        });

        res.print();

        env.execute();

    }
}
